﻿using CRL.Data.LambdaQuery;
using Nest;
using System;
using System.Collections.Generic;
using System.Linq.Expressions;
using System.Text;

namespace CRL.Elasticsearch
{
    public class BoolQueryCreater<T> : BoolQuery
    {
        ESLambdaQuery<T> _query;
        internal Expression<Func<T, bool>> filter;
        internal Expression<Func<T, bool>> must;
        internal Expression<Func<T, bool>> mustNot;
        internal Expression<Func<T, bool>> should;
        internal MinimumShouldMatch minimumShouldMatch;
        public BoolQueryCreater(ILambdaQuery<T> query)
        {
            _query = query as ESLambdaQuery<T>;
        }
        public BoolQueryCreater<T> SetFilter(Expression<Func<T, bool>> expression)
        {
            filter = expression;
            Filter = getFilter(_query, expression);
            return this;
        }
        public BoolQueryCreater<T> SetMust(Expression<Func<T, bool>> expression)
        {
            must = expression;
            Must = getFilter(_query, expression);
            return this;
        }
        public BoolQueryCreater<T> SetMustNot(Expression<Func<T, bool>> expression)
        {
            mustNot = expression;
            MustNot = getFilter(_query, expression);
            return this;
        }
        public BoolQueryCreater<T> SetShould(Expression<Func<T, bool>> expression)
        {
            should = expression;
            Should = getFilter(_query, expression);
            return this;
        }
        public BoolQueryCreater<T> SetMinimumShouldMatch(MinimumShouldMatch _minimumShouldMatch)
        {
            minimumShouldMatch = _minimumShouldMatch;
            MinimumShouldMatch = _minimumShouldMatch;
            return this;
        }
        static List<QueryContainer> getFilter(ESLambdaQuery<T> query, Expression<Func<T, bool>> expression)
        {
            if (expression == null)
                return null;
            var crlExpression = query.FormatExpression(expression.Body);
            var filterData = query.RouteCRLExpression(crlExpression);
            return filterData.Filters;
        }
    }
}
